<?php

// Unix timestamp for start of script execution
$startTime = microtime(true);

// Includes
require_once('config.php');
require_once('facebook.php');
require_once('PeDO.php');

// Initialize the session, Facebook SDK object and the database connection
session_start();
$fb = new Facebook(array('appId' => FB_APPID, 'secret' => FB_SECRET));
$db = new PeDO(DB_SOURCE, DB_USERNAME, DB_PASSWORD);

set_error_handler(function($errno, $errstr, $errfile, $errline, $errcontext) {
	appLog("$errfile:$errline -> $errstr ($errno)", 'Error');
	return false;
});

set_exception_handler(function($e) {
	appLog($e);
});

// Function for URL redirection
function redirect($url, $reason = null, $top = false) {
	header('Location: ' . WEB_URL . 'redirect.php?url=' . urlencode($url) . '&reason=' . urlencode($reason) . '&top=' . urlencode($top) . '&hash=' . md5($url . session_id() . FB_SECRET));
	exit;
}

// Function for logging
function appLog($e, $type = 'Notice') {
	if (is_object($e)) {
		$GLOBALS['db']->q('INSERT INTO app_log(type, message) VALUES(?, ?)', 'Exception', $e->getMessage() . "\n= Trace =\n" . $e->getTraceAsString() . ')');
	} else {
		$stack = array_reverse(debug_backtrace());
		$sourceLines = array();
		foreach ($stack as $frame) $sourceLines[] = basename($frame['file']) . ":$frame[line]";
		$GLOBALS['db']->q('INSERT INTO app_log(type, message) VALUES(?, ?)', $type, implode(' -> ', $sourceLines) . '::' . $e);
	}
}

?>